﻿#include "excelutil.h"
#include <QFile>

#include "QtXlsxWriter/src/xlsx/xlsxdocument.h"
#include "QtXlsxWriter/src/xlsx/xlsxcellrange.h"
#include "QtXlsxWriter/src/xlsx/xlsxrichstring.h"
#include "QtXlsxWriter/src/xlsx/xlsxworkbook.h"
#include "QtXlsxWriter/src/xlsx/xlsxchart.h"
using namespace QXlsx;

ExcelUtil::ExcelUtil()
{

}

ExcelUtil* ExcelUtil::instance(){
    return excelInstance();  // 返回线程安全的静态对象
}


//导出文件
bool ExcelUtil::exportExcelFile(QString fileName, QList<QStringList> dataList)
{
    Document xlsx;
    if (!xlsx.addSheet("sheet1")){
        return false;
    }

    if(dataList.size() == 0)
    {
        return xlsx.saveAs(fileName);
    }

    QStringList headList = dataList.at(0);

    char colA = 'A';
    for(int i=0; i<headList.count(); i++)
    {
        char col = colA + i;
        QString cell = QString(col) + QString("1");
        xlsx.write(cell, headList.at(i));
    }

    for(int index=1; index<dataList.count(); index++)
    {
        for(int i=0; i<headList.count(); i++)
        {
            char col = colA + i;
            QString cell = QString(col) + QString::number(1+index);
            xlsx.write(cell, dataList[index][i]);
        }
    }
    return xlsx.saveAs(fileName);
}

//导出文件
bool ExcelUtil::exportCsvFile(QString fileName, QList<QStringList> dataList)
{
    QFile file(fileName);
    if(!file.open(QIODevice::WriteOnly))
        return false;

    for(int index=0; index<dataList.count(); index++)
    {
        QStringList data = dataList.at(index);
        QString line = data.join(',') + '\r\n';
        file.write(line.toLocal8Bit());
    }
    file.close();
    return true;
}
